package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.AndroidVersions;
import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.fntech.m10.gpio.M10_GPIO;
import com.fntech.m10a.gpio.M10A_GPIO;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.rfid.m10.u8.service.IOManager;
import com.zjlanyun.erp.rfid.m10.u8.service.SoundManager;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.ViewUtil;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

//在线检验
public class LoadingCheck extends BaseRFIDActivity {

    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_FDevNumber) TextView tv_FDevNumber;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.et_FBatchNO) EditText et_FBatchNO;
    @Bind(R.id.et_FTime) EditText et_FTime;
    @Bind(R.id.et_FMacSpeed) EditText et_FMacSpeed;
    @Bind(R.id.et_FWeight1) EditText et_FWeight1;
    @Bind(R.id.et_FWeight2) EditText et_FWeight2;
    @Bind(R.id.et_FWeight3) EditText et_FWeight3;
    @Bind(R.id.et_FCLQty) EditText et_FCLQty;
//    @Bind(R.id.et_FQty) EditText et_FQty;
//    @Bind(R.id.et_FSaleStand) EditText et_FSaleStand;
    @Bind(R.id.et_FNote) EditText et_FNote;
    @Bind(R.id.et_FQCName) EditText et_FQCName;
//    @Bind(R.id.et_FTuiqty) EditText et_FTuiqty;
//    @Bind(R.id.et_FTuiweight) EditText et_FTuiweight;
    @Bind(R.id.et_FPihao) EditText et_FPihao;
    @Bind(R.id.et_FKuanfu) EditText et_FKuanfu;
    @Bind(R.id.et_FFuzhuoli) EditText et_FFuzhuoli;
    @Bind(R.id.et_FZhongliang) EditText et_FZhongliang;
    @Bind(R.id.et_FHoudu) EditText et_FHoudu;
    @Bind(R.id.et_FLaodu) EditText et_FLaodu;
//    @Bind(R.id.et_FZhangli) EditText et_FZhangli;
    @Bind(R.id.et_FBaidu) EditText et_FBaidu;
    @Bind(R.id.et_Fylhoudu1) EditText et_Fylhoudu1;
    @Bind(R.id.et_Fylhoudu2) EditText et_Fylhoudu2;
    @Bind(R.id.et_Fylhoudu3) EditText et_Fylhoudu3;
    @Bind(R.id.tv_FUnit) TextView tv_FUnit;
    @Bind(R.id.btn_selectbanci) Button btn_selectbanci;

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";
    private String FWorkShift = ""; //班次
    private ArrayList<HashMap<String, Object>> mBanciList; //班次
    private ArrayList<HashMap<String, Object>> mQcnameList; //质检员
    public static SoundManager mSoundManager = new SoundManager();
    private String barcode = "";

    public static final int REQUESTCODE_BANCI = 1;
    public static final int REQUESTCODE_QCNAME = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading_check);
        initBaseView();
        initView();
        initScan();
    }

    private void initView() {
        apiUrl = WebApi.production();
        ll_submit.setVisibility(View.VISIBLE);
        title.setText("在线检验");
        //初始化班次
        if (!AppConfig.getInstance().getString("FWorkShift", "").equals("")) {
            FWorkShift = AppConfig.getInstance().getString("FWorkShift", "");
            btn_selectbanci.setText(FWorkShift);
        }

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!et_FBatchNO.getText().toString().equals("")) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    private void initScan() {
        mSoundManager.initSounds(this);
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOn();
            IOManager.INSTANCE.InitComm(handler);
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOn();
            IOManager.INSTANCE.InitCommA(handler);
        }
    }

    @Override
    protected void onResume() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOn();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOn();
        }
        super.onResume();
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            epc = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            getProductInfo();
        }
    }

    /**
     * 获取产品信息
     */
    private void getProductInfo() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FGongXuNO", "110");
        param.put("FActionFlag", "loadingCheck");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getProductInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                tv_epc.setText(data.optString("epc"));
                tv_FName.setText(data.optString("FName"));
                tv_FNumber.setText(data.optString("FNumber"));
                et_FBatchNO.setText(data.optString("FBatchNO"));
                et_FMacSpeed.setText(data.optString("FMacSpeed"));
                tv_FDevNumber.setText(data.optString("FDevNumber"));
                tv_FGongxuName.setText(data.optString("FGongxuName"));
                et_FTime.setText(data.optString("datetime"));
                tv_FUnit.setText(data.optString("FUnit"));

//                et_FQCName.setText(AppConfig.getInstance().getString("username", ""));

                mBanciList = new ArrayList<>();
                JSONArray banci = data.optJSONArray("banci");
                for (int i = 0; i < banci.length(); i++) {
                    JSONObject item = banci.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    mBanciList.add(map);
                }

                //质检员
                mQcnameList = new ArrayList<>();
                JSONArray qcname = data.optJSONArray("emp");
                for (int i = 0; i < qcname.length(); i++) {
                    JSONObject item = qcname.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    mQcnameList.add(map);
                }
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                clean();
            }
        });
    }

    @OnClick(R.id.ll_submit)
    public void postLoadingCheck() {
        ViewUtil.hideInputMethod(mContext, ll_back);
        if (tv_epc.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请先扫卡");
            return;
        } else if (FWorkShift.equals("")) {
            Toastor.getInstance().showShortToast("请选择班次");
            return;
        } else if (et_FQCName.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请选择质检员");
            return;
        }

//        double FTuiqty, FTuiweight;
//        if (et_FTuiqty.getText().toString().equals("")) {
//            FTuiqty = 0;
//        } else {
//            FTuiqty = Double.valueOf(et_FTuiqty.getText().toString());
//        }
//        if (et_FTuiweight.getText().toString().equals("")) {
//            FTuiweight = 0;
//        } else {
//            FTuiweight = Double.valueOf(et_FTuiweight.getText().toString());
//        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("FDevNumber", tv_FDevNumber.getText().toString().equals("")?0:tv_FDevNumber.getText().toString());
        param.put("FBatchNO", et_FBatchNO.getText().toString().replace(" ", "").toUpperCase());
        param.put("FTimeStr", et_FTime.getText().toString());
        param.put("FMacSpeed", et_FMacSpeed.getText().toString());
        param.put("FWeight1", et_FWeight1.getText().toString().equals("")?0:et_FWeight1.getText().toString());
        param.put("FWeight2", et_FWeight2.getText().toString().equals("")?0:et_FWeight2.getText().toString());
        param.put("FWeight3", et_FWeight3.getText().toString().equals("")?0:et_FWeight3.getText().toString());
        param.put("FCLQty", et_FCLQty.getText().toString().equals("")?0:et_FCLQty.getText().toString());
//        param.put("FQty", et_FQty.getText().toString());
//        param.put("FSaleStand", et_FSaleStand.getText().toString());
        param.put("FNote", et_FNote.getText().toString());
        param.put("FQCName", et_FQCName.getText().toString());
        param.put("FPihao", et_FPihao.getText().toString());
        param.put("FKuanfu", et_FKuanfu.getText().toString());
        param.put("FFuzhuoli", et_FFuzhuoli.getText().toString());
        param.put("FZhongliang", et_FZhongliang.getText().toString());
        param.put("FHoudu", et_FHoudu.getText().toString());
        param.put("FLaodu", et_FLaodu.getText().toString());
//        param.put("FZhangli", et_FZhangli.getText().toString());
        param.put("FBaidu", et_FBaidu.getText().toString());
        param.put("FWorkShift", FWorkShift);
//        param.put("FTuiqty", FTuiqty);
//        param.put("FTuiweight", FTuiweight);
        param.put("Fylhoudu1", et_Fylhoudu1.getText().toString().equals("")?0:et_Fylhoudu1.getText().toString());
        param.put("Fylhoudu2", et_Fylhoudu2.getText().toString().equals("")?0:et_Fylhoudu2.getText().toString());
        param.put("Fylhoudu3", et_Fylhoudu3.getText().toString().equals("")?0:et_Fylhoudu3.getText().toString());
        param.put("FGongXuNO", "110");
        param.put("FActionFlag", "loadingCheck");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postLoadingCheck", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(R.string.submit_success);
                AppConfig.getInstance().putString("FWorkShift", FWorkShift);
                clean();
            }
        });

    }

    /**
     * 选择班次
     */
    @OnClick(R.id.btn_selectbanci)
    public void select_banci() {
        if (mBanciList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择班次");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mBanciList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_BANCI);
        } else {
            Toastor.getInstance().showShortToast("无班次数据，请先扫卡");
        }
    }

    /**
     * 选择质检员
     */
    @OnClick(R.id.btn_select_qcname)
    public void select_qcname() {
        if (mQcnameList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择质检员");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mQcnameList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_QCNAME);
        } else {
            Toastor.getInstance().showShortToast("无质检员信息，请先扫卡");
        }
    }

    private void clean() {
        tv_epc.setText("");
        tv_FDevNumber.setText("");
        tv_FName.setText("");
        tv_FNumber.setText("");
        et_FBatchNO.setText("");
        et_FTime.setText("");
        et_FMacSpeed.setText("");
        et_FWeight1.setText("");
        et_FWeight2.setText("");
        et_FWeight3.setText("");
        et_FCLQty.setText("");
//        et_FQty.setText("");
//        et_FSaleStand.setText("");
        et_FNote.setText("");
        et_FQCName.setText("");
//        et_FTuiweight.setText("");
//        et_FTuiqty.setText("");
        et_FPihao.setText("");
        et_FKuanfu.setText("");
        et_FFuzhuoli.setText("");
        et_FZhongliang.setText("");
        et_FHoudu.setText("");
        et_FLaodu.setText("");
//        et_FZhangli.setText("");
        et_FBaidu.setText("");
        et_Fylhoudu1.setText("");
        et_Fylhoudu2.setText("");
        et_Fylhoudu3.setText("");
        tv_FGongxuName.setText("");
        epc = "";
        barcode = "";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!et_FBatchNO.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        } else if ((keyCode == 21 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 22 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            writeFile("/sys/class/gpio/gpio907/direction", "out");
            writeFile("/sys/class/gpio/gpio907/value", "0");
            writeFile("/sys/class/gpio/gpio909/value", "1");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if ((keyCode == 21 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 22 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            writeFile("/sys/class/gpio/gpio907/value", "1");
            writeFile("/sys/class/gpio/gpio909/value", "1");
            return false;
        }
        return super.onKeyUp(keyCode, event);
    }

    private static void writeFile(String fileName, String writestr) {
        try {
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = writestr.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    byte[] ret = (byte[]) msg.obj;
                    try {
                        barcode = new String(ret, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    et_FPihao.setText(barcode);
                    mSoundManager.playSound();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOff();
            IOManager.INSTANCE.DeInitComm();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOff();
            IOManager.INSTANCE.DeInitCommA();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_BANCI && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            btn_selectbanci.setText(mBanciList.get(p).get("FName").toString());
            FWorkShift = mBanciList.get(p).get("FName").toString();
        } else if (requestCode == REQUESTCODE_QCNAME && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            et_FQCName.setText(mQcnameList.get(p).get("FName").toString());
        }
    }
}
